<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="personName">
        <el-input
          v-model="queryParams.personName"
          placeholder="请输入姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属企业" prop="companyName" style="width: 20%">
        <el-select v-model="queryParams.companyName" style="width: 120%" placeholder="请搜索选择所属企业" filterable
                   remote
                   :remote-method="handleSearchCompanies" :loading="loadingCompanies" @change="handleQuery"
                   popper-append-to-body clearable
        >
          <el-option v-for="item in companyList" :key="item.id" :label="item.companyName" :value="item.companyName"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否绑定微信" prop="isBindWechat" label-width="120px">
        <el-select v-model="queryParams.isBindWechat" placeholder="请选择是否绑定微信" clearable size="small"
                   @change="handleQuery"
        >
          <el-option label="是" value="是"/>
          <el-option label="否" value="否"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['union:card:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['union:card:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['union:card:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col v-if="false" :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['union:card:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="cardList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" width="60" align="center" prop="id"/>
      <el-table-column label="姓名" align="center" prop="personName"/>
      <el-table-column label="手机号" align="center" prop="mobilePhone"/>
      <el-table-column label="所属企业" align="center" prop="companyName"/>
      <el-table-column label="是否绑定微信" align="center" prop="isBindWechat"/>
      <el-table-column label="创建时间" align="center" prop="createTime"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="false"
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['union:card:query']"
          >查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['union:card:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['union:card:remove']"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleUnbinding(scope.row)"
            v-hasPermi="['union:card:edit']"
            v-if="scope.row.isBindWechat === '是'"
          >解绑微信
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改个人名片信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1250px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="姓名" prop="personName">
              <el-input v-model="form.personName" placeholder="请输入姓名" :disabled="viewopen"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商会任职" prop="chamberPosition">
              <el-input v-model="form.chamberPosition" placeholder="请输入商会任职" :disabled="viewopen"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机号" prop="mobilePhone">
              <el-input v-model="form.mobilePhone" placeholder="请输入手机号" :disabled="viewopen"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系方式" prop="contactInfo">
              <el-input v-model="form.contactInfo" placeholder="请输入联系方式" :disabled="viewopen"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" :disabled="viewopen"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="个人名片" prop="businessCard">
              <el-upload
                :file-list="fileList"
                :action="uploadUrl"
                accept="image/jpeg,image/png"
                ref="singleUpload"
                class="avatar-uploader2"
                :limit="1"
                list-type="picture-card"
                :before-upload="beforeAvatarUpload"
                :on-progress="onLoading"
                :on-error="onPhotoError"
                :on-success="handlePhotoSuccess"
                :on-remove="handlePhotoRemove"
                :multiple="false"
                :on-exceed="handleExceed"
                :disabled="viewopen"
              >
                <!-- 上传按钮（仅当没有文件时显示） -->
                <i class="el-icon-plus"></i>
                <!-- 自定义提示文字 -->
                <div slot="tip" class="el-upload__tip">
                  支持上传jpg/png图片，且不超过500kb
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="二维码" prop="qrCode">
              <el-upload
                :file-list="fileList1"
                :action="uploadUrl"
                accept="image/jpeg,image/png"
                ref="singleUpload"
                class="avatar-uploader2"
                :limit="1"
                list-type="picture-card"
                :before-upload="beforeAvatarUpload"
                :on-progress="onLoading"
                :on-error="onPhotoError"
                :on-success="handlePhotoSuccess1"
                :on-remove="handlePhotoRemove1"
                :multiple="false"
                :on-exceed="handleExceed"
                :disabled="viewopen"
              >
                <!-- 上传按钮（仅当没有文件时显示） -->
                <i class="el-icon-plus"></i>
                <!-- 自定义提示文字 -->
                <div slot="tip" class="el-upload__tip">
                  支持上传jpg/png图片，且不超过500kb
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="所属企业" prop="companyName">
              <el-select v-model="form.companyName" style="width: 100%" placeholder="请搜索选择所属企业" filterable
                         remote
                         :remote-method="handleSearchCompanies" :loading="loadingCompanies"
                         @change="handleCompanySelect" :disabled="viewopen"
              >
                <el-option v-for="item in companyList" :key="item.id" :label="item.companyName" :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业简称" prop="companyAbbreviation">
              <el-input v-model="form.companyAbbreviation" placeholder="请输入企业简称" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注册&办公地址" prop="registrationOfficeAddress">
              <el-input v-model="form.registrationOfficeAddress" type="textarea" rows="2" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业网址" prop="websiteUrl">
              <el-input v-model="form.websiteUrl" type="textarea" placeholder="请输入企业网址" rows="7" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司职位" prop="companyPosition">
              <el-input v-model="form.companyPosition" placeholder="请输入公司职位" :disabled="viewopen"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业logo" prop="companyLogo">
              <img :src="form.companyLogo ? baseUrl + form.companyLogo : require('@/assets/image/click.png')"
                   alt="企业logo" style="width: 80px; height: 80px;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="企业简介" prop="companyProfile">
              <el-input v-model="form.companyProfile" type="textarea" rows="8" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-row :gutter="24" v-if="viewopen">
            <el-col :span="12">
              <el-form-item label="创建人" prop="createBy">
                <el-input v-model="form.createBy" :disabled="viewopen"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="创建时间" prop="createTime">
                <el-input v-model="form.createTime" :disabled="viewopen"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="更新人" prop="updateBy">
                <el-input v-model="form.updateBy" :disabled="viewopen"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="更新时间" prop="updateTime">
                <el-input v-model="form.updateTime" :disabled="viewopen"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="form.isBindWechat === '是'">
              <el-form-item label="微信OPEN_ID" prop="openid">
                <el-input v-model="form.openid" :disabled="viewopen"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-row>
      </el-form>
      <div v-if="!viewopen" slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCompanies,
  getCompanies
} from '@/api/union/companies'
import { listCard, getCard, delCard, addCard, updateCard, exportCard, unbindWechat} from '@/api/union/card'

export default {
  name: 'Card',
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadUrl: process.env.VUE_APP_BASE_API + '/common/upload',
      companyList: [],
      loadingCompanies: false,
      fileList: [],
      fileList1: [],
      images: [],
      images1: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 个人名片信息表格数据
      cardList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      viewopen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        personName: null,
        chamberPosition: null,
        mobilePhone: null,
        contactInfo: null,
        email: null,
        qrCode: null,
        businessCard: null,
        companyName: null,
        registrationOfficeAddress: null,
        companyLogo: null,
        companyPosition: null,
        companyProfile: null,
        openid: null,
        isBindWechat: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        personName: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
          { max: 30, message: '姓名最多可输入30个字符', trigger: 'blur' }
        ],
        contactInfo: [
          { required: true, message: '联系方式不能为空', trigger: 'blur' }
        ],
        mobilePhone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { pattern: /^[0-9]{11}$/, message: '请输入有效的11位手机号', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        companyName: [
          { required: true, message: '请选择所属企业', trigger: 'blur' }
        ],
        companyPosition: [
          { required: true, message: '公司职位不能为空', trigger: 'blur' },
          { max: 50, message: '公司职位最多可输入50个字符', trigger: 'blur' }
        ],
        chamberPosition: [
          { max: 50, message: '商会任职最多可输入50个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    onPhotoError(err, file, fileList) {
      this.loadingModel.close()
    },
    onLoading(event, file, fileList) {
      this.loadingModel = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    /** 查询个人名片信息列表 */
    getList() {
      this.loading = true
      listCard(this.queryParams).then(response => {
        this.cardList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        personName: null,
        chamberPosition: null,
        mobilePhone: null,
        contactInfo: null,
        email: null,
        qrCode: null,
        businessCard: null,
        companyName: null,
        websiteUrl: null,
        companyAbbreviation: null,
        registrationOfficeAddress: null,
        companyLogo: null,
        companyPosition: null,
        companyProfile: null,
        openid: null,
        createTime: null,
        isBindWechat: null,
        updateTime: null,
        createBy: null,
        updateBy: null
      }
      this.images = []
      this.fileList = []
      this.images1 = []
      this.fileList1 = []
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.viewopen = false
      this.title = '添加个人名片信息'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getCard(id).then(response => {
        this.form = response.data
        // 回显图片
        this.images = []
        this.images1 = []
        this.fileList = []
        this.fileList1 = []
        if (response.data.businessCard != null) {
          this.images.push(response.data.businessCard)
          this.fileList.push({ url: this.baseUrl + response.data.businessCard })
        }
        if (response.data.qrCode != null) {
          this.images1.push(response.data.qrCode)
          this.fileList1.push({ url: this.baseUrl + response.data.qrCode })
        }
        this.open = true
        this.viewopen = false
        this.title = '修改个人名片信息'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          // 如果images为空,则赋值为null, 否则将数组第一个值赋值给form.businessCard
          if (this.images.length === 0) {
            this.form.businessCard = null
          } else {
            this.form.businessCard = this.images[0]
          }
          // 如果images为空,则赋值为null, 否则将数组第一个值赋值给form.businessCard
          if (this.images1.length === 0) {
            this.form.qrCode = null
          } else {
            this.form.qrCode = this.images1[0]
          }
          if (this.form.id != null) {
            updateCard(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              }
            })
          } else {
            addCard(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除选中数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delCard(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(function() {
      })
    },
    /** 解绑微信按钮操作 */
    handleUnbinding(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认解绑选中数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return unbindWechat(row)
      }).then(() => {
        this.getList()
        this.msgSuccess('解绑成功')
      }).catch(function() {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有个人名片信息数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return exportCard(queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(function() {
      })
    },
    handleSearchCompanies(query) {
      if (query !== '') {
        this.loadingCompanies = true
        listCompanies({ companyName: query, pageNum: 1, pageSize: 20 }).then(response => {
          this.companyList = response.rows
          this.loadingCompanies = false
        })
      }
    },
    getCompanyDetails(id) {
      getCompanies(id).then(response => {
        this.form.companyName = response.data.companyName
        this.form.registrationOfficeAddress = response.data.registrationOfficeAddress
        this.form.companyLogo = response.data.companyLogo
        this.form.companyProfile = response.data.companyProfile
        this.form.websiteUrl = response.data.websiteUrl
        this.form.companyAbbreviation = response.data.companyAbbreviation
      })
    },
    handleCompanySelect(id) {
      if (id) {
        this.getCompanyDetails(id)
      }
    },
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/jpeg') || file.type.startsWith('image/png')
      const isLt500 = file.size / 1024 / 1024 < 500
      if (!isImage) {
        this.$message.error('只能上传图片文件!')
      }
      if (!isLt500) {
        this.$message.error('上传图片大小不能超过 500k!')
      }
      return isImage && isLt500
    },
    handlePhotoSuccess(res, file) {
      if (res.code === 200) {
        // 更新文件URL（用于预览）
        file.url = this.baseUrl + res.url
        // 保持文件列表始终只有一个文件
        this.fileList = [file]
        this.images = [res.fileName]
      } else {
        this.msgError(res.msg)
      }
      this.loadingModel.close()

    },
    handlePhotoRemove(file, fileList) {
      let url = ''
      if (file.response !== undefined) {
        url = file.response.url
      } else {
        url = file.url
      }
      this.fileList = fileList
      this.images = fileList
    },
    handlePhotoSuccess1(res, file) {
      if (res.code === 200) {
        // 更新文件URL（用于预览）
        file.url = this.baseUrl + res.url
        // 保持文件列表始终只有一个文件
        this.fileList1 = [file]
        this.images1 = [res.fileName]
      } else {
        this.msgError(res.msg)
      }
      this.loadingModel.close()

    },
    handlePhotoRemove1(file, fileList) {
      let url = ''
      if (file.response !== undefined) {
        url = file.response.url
      } else {
        url = file.url
      }
      this.fileList1 = fileList
      this.images1 = fileList
    },
    // 超出数量限制处理
    handleExceed() {
      this.$message.warning('只能上传1个文件，请先删除后再上传')
    },
    handleView(row) {
      this.reset()
      const id = row.id || this.ids
      getCard(id).then(response => {
        this.form = response.data
        // 回显图片
        this.images = []
        this.images1 = []
        this.fileList = []
        this.fileList1 = []
        if (response.data.businessCard != null) {
          this.images.push(response.data.businessCard)
          this.fileList.push({ url: this.baseUrl + response.data.businessCard })
        }
        if (response.data.qrCode != null) {
          this.images1.push(response.data.qrCode)
          this.fileList1.push({ url: this.baseUrl + response.data.qrCode })
        }
        this.open = true
        this.viewopen = true
        this.title = '查看个人名片信息'
      })
    }
  }
}
</script>
